#!/usr/bin/env python3
"""
Streamlit 应用启动脚本
用于启动 RAG-main 项目的 Web UI 界面
"""

import subprocess
import sys
import os
from pathlib import Path

def check_requirements():
    """检查必要的依赖包"""
    required_packages = [
        'streamlit',
        'pandas', 
        'numpy'
    ]
    
    missing_packages = []
    for package in required_packages:
        try:
            __import__(package)
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        print(f"❌ 缺少必要的依赖包: {', '.join(missing_packages)}")
        print("请运行以下命令安装:")
        print(f"pip install {' '.join(missing_packages)}")
        return False
    
    return True

def check_project_structure():
    """检查项目结构"""
    required_paths = [
        "src",
        "data/stock_data",
        "streamlit_app.py"
    ]
    
    missing_paths = []
    for path in required_paths:
        if not Path(path).exists():
            missing_paths.append(path)
    
    if missing_paths:
        print(f"❌ 缺少必要的项目文件/目录: {', '.join(missing_paths)}")
        return False
    
    return True

def main():
    """主函数"""
    print("🚀 启动 RAG-main Streamlit 应用...")
    
    # 检查依赖
    if not check_requirements():
        sys.exit(1)
    
    # 检查项目结构
    if not check_project_structure():
        print("请确保在项目根目录运行此脚本")
        sys.exit(1)
    
    # 设置环境变量
    os.environ['STREAMLIT_SERVER_PORT'] = '8501'
    os.environ['STREAMLIT_SERVER_ADDRESS'] = '0.0.0.0'
    
    # 启动 Streamlit
    try:
        print("✅ 正在启动 Streamlit 服务器...")
        print("🌐 访问地址: http://localhost:8501")
        print("按 Ctrl+C 停止服务器")
        
        subprocess.run([
            sys.executable, "-m", "streamlit", "run", "streamlit_app.py",
            "--server.port", "8501",
            "--server.address", "127.0.0.1",
            "--theme.base", "light",
            "--theme.primaryColor", "#667eea"
        ])
    
    except KeyboardInterrupt:
        print("\n👋 服务器已停止")
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()